#include "ZenLineList.h"

CZenLineList::CZenLineList()
{
	m_pSegmentList  = 0;
	m_NumPoints	    = 0;
	m_bConnected   	= TRUE;
}

CZenLineList::~CZenLineList()
{
	CPointSegment * pSegment = m_pSegmentList;
	CPointSegment * pTempSeg = 0;

	while (pSegment)
	{
		pTempSeg = pSegment->m_pNext;
		delete pSegment;
		pSegment = pTempSeg;
	}
}

HRESULT CZenLineList::AddPoint(float x, float y, float z, D3DCOLOR PointColor)
{
	if (!m_pSegmentList)
	{
		m_pSegmentList = new CPointSegment;
		m_pSegmentList->m_Vertex.m_Position.x = x;
		m_pSegmentList->m_Vertex.m_Position.y = y;
		m_pSegmentList->m_Vertex.m_Position.z = z;

		m_pSegmentList->m_Vertex.m_DiffuseColor	= PointColor;
	}
	else
	{
		CPointSegment * pSegment = m_pSegmentList;
		
		while (pSegment->m_pNext)
		{
			pSegment = pSegment->m_pNext;
		}

		pSegment->m_pNext = new CPointSegment;
		pSegment = pSegment->m_pNext;

		pSegment->m_Vertex.m_Position.x = x;
		pSegment->m_Vertex.m_Position.y = y;
		pSegment->m_Vertex.m_Position.z = z;

		pSegment->m_Vertex.m_DiffuseColor = PointColor;
	}

	m_NumPoints++;

	return S_OK;
}

void CZenLineList::ClearPoints()
{
	CPointSegment * pSegment = m_pSegmentList;
	CPointSegment * pTempSeg = 0;

	while(pSegment)
	{
		pTempSeg = pSegment->m_pNext;
		delete pSegment;
		pSegment = pTempSeg;
	}

	m_pSegmentList	= 0;
	m_NumPoints		= 0;
}

HRESULT CZenLineList::Render()
{
	int						Offset	 = 0;
	BYTE *					pData	 = 0;		
	HRESULT					res		 = 0;
	LPDIRECT3DVERTEXBUFFER8 pVB		 = 0;
	CPointSegment *			pSegment = 0;

	if (!m_pSegmentList)
	{
		return E_FAIL;
	}

	res = zen.m_pDevice->CreateVertexBuffer(sizeof(CZenVertex) * m_NumPoints, D3DUSAGE_WRITEONLY,
											ZENVERTEX_TYPE, D3DPOOL_DEFAULT, &pVB);
	if (FAILED(res))
		return E_FAIL;


	res = pVB->Lock(0, 0, &pData, 0);
	if (FAILED(res))
	{
		pVB->Release();
		return E_FAIL;
	}

	pSegment = m_pSegmentList;	

	while (pSegment)
	{
		CopyMemory(pData + Offset, &(pSegment->m_Vertex), sizeof(CZenVertex));
		pSegment = pSegment->m_pNext;
		Offset += sizeof(CZenVertex);
	}

	pVB->Unlock();

	zen.m_pDevice->SetStreamSource(0, pVB, sizeof(CZenVertex));

	if (m_bConnected)
	{
		zen.m_pDevice->DrawPrimitive(D3DPT_LINESTRIP, 0, m_NumPoints-1);
	}
	else
	{
		zen.m_pDevice->DrawPrimitive(D3DPT_LINELIST, 0, m_NumPoints /2 );
	}

	pVB->Release();

	return S_OK;
}
